// pages/talentpeople/talentpeople.js
const db = wx.cloud.database();
const app = getApp();
const _ = db.command;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    videoList: [], //视频数据
    hkindex: 0, //滑块index
    currentIsLike: false,
    canLike: true
  },

  getBackhome() {
    wx.navigateBack({
      delta: 1,
      fail: res => {
        wx.switchTab({
          url: '/pages/home/home',
        })
      }
    })
  },
  //动态更新当前滑块下标
  bindchange(e) {
    console.log(e);
    let that = this;
    db.collection('videoLikeRecord').where({
      _openid: app.personInfo._openid,
      video_id: that.data.videoList[e.detail.current]._id
    }).get({
      success: res => {
        if (res.data.length == 0) {
          that.setData({
            currentIsLike: false
          })
        } else {
          that.setData({
            currentIsLike: true
          })
        }
      }
    });
    console.log(e.detail);
    var cur = e.detail.current;
    let curVideoContext = wx.createVideoContext("myvideo" + cur + "")
    let lastVideoContext = wx.createVideoContext("myvideo" + this.data.hkindex + "")
    this.setData({
      hkindex: e.detail.current
    })
    //暂停上一条视频
    lastVideoContext.pause();
    //当前视频进度条归零
    curVideoContext.seek(0);
    //当前视频开始播放
    curVideoContext.play();
    let limit = this.data.videoList.length - e.detail.current;
    if (limit == 3) {
      this.getMoreVideo(); //加载更多视频
    }
    // this.qingygnanme();
  },

  like(e) {
    if (this.data.canLike == false) {
      wx.showToast({
        title: '操作频繁',
        icon: "error"
      })
      return;
    }
    let that = this;
    console.log(e.currentTarget.dataset.index);
    let index = e.currentTarget.dataset.index;
    let video_id = that.data.videoList[index]._id;
    db.collection('videoLikeRecord').where({
      _openid: app.personInfo._openid,
      video_id: video_id
    }).get({
      success: res => {
        if (res.data.length == 0) {
          //没点过赞，现在点赞
          db.collection('videoLikeRecord').add({
            data: {
              _openid: app.personInfo._openid,
              video_id: video_id
            },
            success: res => {
              console.log("点赞记录");
            }
          })
          db.collection('video').doc(video_id).update({
            data: {
              likeCount: _.inc(1)
            },
            success: res => {
              that.setData({
                ['videoList[' + index + '].likeCount']: that.data.videoList[index].likeCount + 1,
                currentIsLike: true
              });
              console.log('当前视频点赞数：' + that.data.videoList[index].likeCount);
            }
          })
        } else {
          //点过赞，现在取消点赞
          db.collection('videoLikeRecord').where({
            _openid: app.personInfo._openid,
            video_id: video_id
          }).remove({
            success: res => {
              console.log("删除喜欢记录");
              console.log(res);
            }
          });
          db.collection('video').doc(video_id).update({
            data: {
              likeCount: _.inc(-1)
            },
            success: res => {
              that.setData({
                ['videoList[' + index + '].likeCount']: that.data.videoList[index].likeCount - 1,
                currentIsLike: false
              });
              console.log('当前视频点赞数：' + that.data.videoList[index].likeCount);
            }
          })
        }
      },
      complete: () => {
        that.setData({
          canLike: false
        })
        setTimeout(function (res) {
          that.setData({
            canLike: true
          })
        }, 3000)
      }
    })
  },
  share() {
    console.log("分享");
    console.log(this.data.videoList[this.data.hkindex].title);
  },



  //-----------------------------------------------------
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    let that = this;
    if (options.video_id) {
      let id = options.video_id;
      db.collection('video').doc(id).get({
        success: res => {
          let arr = [res.data];
          that.setData({
            videoList: arr
          });
          wx.showToast({
            icon: "none",
            title: '点击分享链接进入的用户只能查看一条视频哦，如果想看更多视频请点返回重新进入',
            duration: 6000
          })
        },
        fail: res => {
          console.log(res);
        }
      });
    } else {
      wx.cloud.callFunction({
        name: 'getAllRecord',
        data: {
          collectionName: 'video'
        },
        success: res => {
          console.log(res.result.all);
          that.setData({
            videoList: res.result.all
          });
          db.collection('videoLikeRecord').where({
            _openid: app.personInfo._openid,
            video_id: that.data.videoList[0]._id
          }).get({
            success: res => {
              if (res.data.length == 0) {
                that.setData({
                  currentIsLike: false
                })
              } else {
                that.setData({
                  currentIsLike: true
                })
              }
            }
          })

        },
        complete: () => {
          // 做个延时，不然无效
          setTimeout(function () {
            //页面进入就开启播放
            that.bindchange({
              detail: {
                current: '0'
              }
            });
          }, 1000)

        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击分享
   */
  onShareAppMessage() {
    let that = this;
    // 没有成功与失败的回调函数，妥协，只能点一下按钮算一次分享

    db.collection('video').doc(that.data.videoList[that.data.hkindex]._id).update({
      data: {
        shareCount: _.inc(1)
      },
      success: res => {
        console.log("分享成功");
        that.setData({
          ['videoList[' + that.data.hkindex + '].shareCount']: that.data.videoList[that.data.hkindex].shareCount + 1,
        });
        console.log('当前视频分享数：' + that.data.videoList[that.data.hkindex].shareCount);
      },
      fail: res => {
        console.log(res)
      }
    })

    return {
      title: "农学僧 - 小农达人 -" + that.data.videoList[that.data.hkindex].title,
      path: 'pages/talentpeople/talentpeople?video_id=' + that.data.videoList[that.data.hkindex]._id,
      imageUrl: that.data.videoList[that.data.hkindex].src,
    }

  }



})